package com.project.demo.controller;

import com.project.demo.entity.UserMessage;
import com.project.demo.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户消息：(UserMessage)表控制层
 */
@Slf4j
@RestController
@RequestMapping("/user_message")
public class UserMessageController extends BaseController<UserMessage, com.project.demo.service.base.BaseService<UserMessage>> {

    @Autowired
    public UserMessageController(com.project.demo.service.impl.UserMessageServiceImpl service) {
        setService(service);
    }

    /**
     * 获取当前用户的消息列表
     */
    @RequestMapping("/get_my_messages")
    public Map<String, Object> getMyMessages(HttpServletRequest request) {
        try {
            // 获取当前登录用户ID
            Integer userId = getLoginUserId(request);
            if (userId == null || userId == 0) {
                return error(401, "请先登录");
            }

            Map<String, String> query = new HashMap<>();
            query.put("user_id", userId.toString());
            
            Map<String, String> config = new HashMap<>();
            config.put("order", "create_time desc");

            Query result = service.select(query, config);
            List<?> list = result != null ? result.getResultList() : null;

            Map<String, Object> data = new HashMap<>();
            data.put("list", list);
            data.put("count", list != null ? list.size() : 0);

            // 统计未读消息数
            Map<String, String> unreadQuery = new HashMap<>();
            unreadQuery.put("user_id", userId.toString());
            unreadQuery.put("is_read", "0");
            Map<String, String> unreadConfig = new HashMap<>(); // 传递空配置而不是 null
            Query unreadResult = service.count(unreadQuery, unreadConfig);
            Object unreadCountObj = unreadResult != null ? unreadResult.getSingleResult() : null;
            int unreadCount = 0;
            if (unreadCountObj instanceof Number) {
                unreadCount = ((Number) unreadCountObj).intValue();
            }
            data.put("unread_count", unreadCount);

            return success(data);
        } catch (Exception e) {
            log.error("获取用户消息列表失败", e);
            return error(500, "获取消息列表失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     */
    @PostMapping("/mark_as_read")
    public Map<String, Object> markAsRead(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 从请求体或查询参数中获取 message_id
            String messageId = null;
            if (bodyMap != null && bodyMap.get("message_id") != null) {
                messageId = bodyMap.get("message_id").toString();
            } else {
                Map<String, String> query = service.readQuery(request);
                messageId = query.get("message_id");
            }
            
            if (messageId == null || messageId.isEmpty()) {
                return error(400, "message_id 不能为空");
            }

            // 获取当前登录用户ID（优先从请求体中获取，否则从查询参数）
            Integer userId = null;
            if (bodyMap != null && bodyMap.get("user_id") != null) {
                try {
                    userId = Integer.parseInt(bodyMap.get("user_id").toString());
                } catch (NumberFormatException e) {
                    log.warn("请求体中的 user_id 格式错误: {}", bodyMap.get("user_id"));
                }
            }
            
            // 如果从请求体中获取不到，尝试从查询参数获取
            if (userId == null || userId == 0) {
                userId = getLoginUserId(request);
            }
            
            if (userId == null || userId == 0) {
                return error(401, "请先登录");
            }

            // 验证消息属于当前用户
            Map<String, String> checkQuery = new HashMap<>();
            checkQuery.put("message_id", messageId);
            checkQuery.put("user_id", userId.toString());
            Map<String, String> checkConfig = new HashMap<>(); // 传递空配置而不是 null
            Query checkResult = service.select(checkQuery, checkConfig);
            Object messageObj = checkResult != null ? checkResult.getSingleResult() : null;
            
            if (messageObj == null) {
                log.warn("标记已读失败：消息不存在或无权限 - message_id: {}, user_id: {}", messageId, userId);
                return error(404, "消息不存在或无权限");
            }

            // 更新为已读
            Map<String, String> updateConfig = new HashMap<>();
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("is_read", 1);
            service.update(checkQuery, updateConfig, updateData);

            log.info("标记消息已读成功 - message_id: {}, user_id: {}", messageId, userId);
            return success("标记已读成功");
        } catch (Exception e) {
            log.error("标记消息为已读失败", e);
            return error(500, "标记失败: " + e.getMessage());
        }
    }

    /**
     * 标记所有消息为已读
     */
    @PostMapping("/mark_all_as_read")
    public Map<String, Object> markAllAsRead(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 获取当前登录用户ID（优先从请求体中获取，否则从查询参数）
            Integer userId = null;
            if (bodyMap != null && bodyMap.get("user_id") != null) {
                try {
                    userId = Integer.parseInt(bodyMap.get("user_id").toString());
                } catch (NumberFormatException e) {
                    log.warn("请求体中的 user_id 格式错误: {}", bodyMap.get("user_id"));
                }
            }
            
            // 如果从请求体中获取不到，尝试从查询参数获取
            if (userId == null || userId == 0) {
                userId = getLoginUserId(request);
            }
            
            if (userId == null || userId == 0) {
                return error(401, "请先登录");
            }

            // 更新该用户的所有未读消息为已读
            Map<String, String> query = new HashMap<>();
            query.put("user_id", userId.toString());
            query.put("is_read", "0");
            
            Map<String, String> updateConfig = new HashMap<>();
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("is_read", 1);
            service.update(query, updateConfig, updateData);

            log.info("全部标记已读成功 - user_id: {}", userId);
            return success("全部标记已读成功");
        } catch (Exception e) {
            log.error("标记所有消息为已读失败", e);
            return error(500, "标记失败: " + e.getMessage());
        }
    }

    /**
     * 获取未读消息数量
     */
    @RequestMapping("/get_unread_count")
    public Map<String, Object> getUnreadCount(HttpServletRequest request) {
        try {
            // 获取当前登录用户ID
            Integer userId = getLoginUserId(request);
            if (userId == null || userId == 0) {
                return success(0);
            }

            Map<String, String> query = new HashMap<>();
            query.put("user_id", userId.toString());
            query.put("is_read", "0");
            
            Map<String, String> config = new HashMap<>(); // 传递空配置而不是 null
            Query result = service.count(query, config);
            Object countObj = result != null ? result.getSingleResult() : null;
            int count = 0;
            if (countObj instanceof Number) {
                count = ((Number) countObj).intValue();
            }

            return success(count);
        } catch (Exception e) {
            log.error("获取未读消息数量失败", e);
            return success(0);
        }
    }

    /**
     * 删除消息（只能删除自己的消息）
     */
    @RequestMapping("/del")
    @Transactional
    public Map<String, Object> del(HttpServletRequest request) {
        try {
            Map<String, String> query = service.readQuery(request);
            String messageId = query.get("message_id");
            
            if (messageId == null || messageId.isEmpty()) {
                return error(400, "message_id 不能为空");
            }

            // 获取当前登录用户ID
            Integer userId = getLoginUserId(request);
            if (userId == null || userId == 0) {
                return error(401, "请先登录");
            }

            // 验证消息属于当前用户
            Map<String, String> checkQuery = new HashMap<>();
            checkQuery.put("message_id", messageId);
            checkQuery.put("user_id", userId.toString());
            Map<String, String> checkConfig = new HashMap<>();
            Query checkResult = service.select(checkQuery, checkConfig);
            Object messageObj = checkResult != null ? checkResult.getSingleResult() : null;
            
            if (messageObj == null) {
                return error(404, "消息不存在或无权限");
            }

            // 删除消息
            service.delete(checkQuery, checkConfig);

            log.info("删除消息成功 - message_id: {}, user_id: {}", messageId, userId);
            return success("删除成功");
        } catch (Exception e) {
            log.error("删除消息失败", e);
            return error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 批量删除消息（只能删除自己的消息）
     */
    @PostMapping("/batch_delete")
    public Map<String, Object> batchDelete(HttpServletRequest request) {
        try {
            // 先尝试从请求体读取（POST数据）
            Map<String, Object> bodyMap = null;
            try {
                bodyMap = service.readBody(request.getReader());
            } catch (Exception e) {
                log.debug("读取请求体失败，尝试从查询参数读取: {}", e.getMessage());
            }
            
            // 获取消息ID列表
            List<Integer> messageIds = new ArrayList<>();
            if (bodyMap != null && bodyMap.get("message_ids") != null) {
                Object messageIdsObj = bodyMap.get("message_ids");
                if (messageIdsObj instanceof List<?>) {
                    for (Object id : (List<?>) messageIdsObj) {
                        if (id != null) {
                            try {
                                messageIds.add(Integer.parseInt(id.toString()));
                            } catch (NumberFormatException e) {
                                log.warn("无效的消息ID: {}", id);
                            }
                        }
                    }
                }
            }
            
            if (messageIds.isEmpty()) {
                return error(400, "请选择要删除的消息");
            }

            // 获取当前登录用户ID
            Integer userId = null;
            if (bodyMap != null && bodyMap.get("user_id") != null) {
                try {
                    userId = Integer.parseInt(bodyMap.get("user_id").toString());
                } catch (NumberFormatException e) {
                    log.warn("请求体中的 user_id 格式错误: {}", bodyMap.get("user_id"));
                }
            }
            
            if (userId == null || userId == 0) {
                userId = getLoginUserId(request);
            }
            
            if (userId == null || userId == 0) {
                return error(401, "请先登录");
            }

            // 验证所有消息都属于当前用户，并删除
            int deletedCount = 0;
            for (Integer messageId : messageIds) {
                Map<String, String> checkQuery = new HashMap<>();
                checkQuery.put("message_id", messageId.toString());
                checkQuery.put("user_id", userId.toString());
                Map<String, String> checkConfig = new HashMap<>();
                Query checkResult = service.select(checkQuery, checkConfig);
                Object messageObj = checkResult != null ? checkResult.getSingleResult() : null;
                
                if (messageObj != null) {
                    service.delete(checkQuery, checkConfig);
                    deletedCount++;
                }
            }

            log.info("批量删除消息成功 - user_id: {}, 删除数量: {}/{}", userId, deletedCount, messageIds.size());
            return success("成功删除 " + deletedCount + " 条消息");
        } catch (Exception e) {
            log.error("批量删除消息失败", e);
            return error(500, "删除失败: " + e.getMessage());
        }
    }

    /**
     * 获取当前登录用户ID
     */
    private Integer getLoginUserId(HttpServletRequest request) {
        try {
            // 从请求参数中获取 user_id（前端会在请求中传递）
            String userIdStr = request.getParameter("user_id");
            if (userIdStr == null || userIdStr.isEmpty()) {
                // 尝试从请求体或查询参数中获取
                Map<String, String> query = service.readQuery(request);
                userIdStr = query.get("user_id");
            }
            
            if (userIdStr != null && !userIdStr.isEmpty()) {
                return Integer.parseInt(userIdStr);
            }
            
            log.warn("无法获取用户ID，请确保前端传递了 user_id 参数");
            return null;
        } catch (Exception e) {
            log.warn("获取用户ID失败", e);
            return null;
        }
    }
}

